package cn.tnar.parkservice.controller.financia;

import cn.tnar.parkservice.model.dto.InvoiceDetailDTO;
import cn.tnar.parkservice.model.entity.TApplyTicketAcctInfo;
import cn.tnar.parkservice.model.entity.TInvoiceRelation;
import cn.tnar.parkservice.model.request.InvoiceRedRequest;
import cn.tnar.parkservice.model.request.ParkDayHighparkingRecordRequest;
import cn.tnar.parkservice.model.response.InvoiceDetailResponse;
import cn.tnar.parkservice.model.response.ParkInfoInResponse;
import cn.tnar.parkservice.service.BWInvoiceService;
import cn.tnar.parkservice.service.ITApplyTicketAcctInfoService;
import cn.tnar.parkservice.service.ITParkInfoService;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zzb
 * @since 2019-03-27
 */
@Api(tags = "百旺发票配置")
@RestController
@RequestMapping("service/tApplyTicket")
public class TApplyTicketAcctInfoController {

    private Logger logger = LoggerFactory.getLogger(TApplyTicketAcctInfoController.class);

    @Autowired
    @Qualifier("tApplyTicketAcctInfoServiceImpl")
    private ITApplyTicketAcctInfoService service;

    @Autowired
    private ITParkInfoService itParkInfoService;

    @Autowired
    private BWInvoiceService invoiceService;

    private ResultJson json = new ResultJson();

    @ApiOperation(value = "查询(分页)")
    @PostMapping("/query")
    public ResultJson query(@RequestBody ParkDayHighparkingRecordRequest info) {
        if (info.getParkCode() == null) {
            return json.setCode(900).setMsg("请选择停车场").setData(null);
        }
        Page<TApplyTicketAcctInfo> list = service.query(info);
        return json.setCode(200).setMsg("查询成功").setData(list);

    }

    @ApiOperation(value = "筛选已配置的停车场")
    @PostMapping("/queryParkInfo")
    public ResultJson queryParkInfo(@RequestBody ParkDayHighparkingRecordRequest info) {
        if (info.getParkCode() == null || info.getParkCode() == "") {
            return json.setCode(900).setMsg("请选择停车场").setData(null);
        }

        String[] split = info.getParkCode().split(",");
        List<String> splitList = new ArrayList<>(Arrays.asList(split));

        Iterator<String> it = splitList.iterator();
        while(it.hasNext()){
            String parkCode= it.next();
            QueryWrapper<TApplyTicketAcctInfo> queryWrapper = new QueryWrapper();
            queryWrapper.eq("delflag", 1)
                    .eq("park_code", parkCode);
            List<TApplyTicketAcctInfo> list = service.list(queryWrapper);
            if (list.size() > 0) {
                it.remove();
            }
        }

        if (splitList.size() > 0) {
            String[] strArray = splitList.toArray(new String[splitList.size()]);
            String parkCodes = Arrays.toString(strArray).replaceAll("\\[", "").replaceAll("\\]", "");
            List<ParkInfoInResponse> parkInfoIn = itParkInfoService.getParkInfoIn(parkCodes);
            return json.setCode(200).setMsg("查询成功").setData(parkInfoIn);
        } else {
            return json.setCode(900).setMsg("停车场均已配置").setData(null);
        }


    }


    @ApiOperation(value = "新增")
    @PostMapping("/insert")
    public ResultJson insert(@RequestBody TApplyTicketAcctInfo info) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Long nowLong = new Long(sdf.format(new Date()));
        info.setId(0L);
        info.setVersion("0");
        info.setFpqqlsh("0");
        info.setDsptbm("0");
        info.setNsrsbh("0");
        info.setNsrmc("0");
        info.setXhfDz("0");
        info.setXhfDh("0");
        info.setXhfYhzh("0");
        info.setCreateTime(nowLong);
        boolean save = service.save(info);
        if (save) {
            return json.setCode(200).setMsg("新增成功").setData(null);

        } else {
            return json.setCode(900).setMsg("新增失败").setData(null);
        }
    }

    @ApiOperation(value = "修改/删除")
    @PostMapping("/update")
    public ResultJson update(@RequestBody TApplyTicketAcctInfo info) {
        //删除时delflag=0
        if (info.getId() == null) {
            return json.setCode(900).setMsg("id不能为空").setData(null);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Long nowLong = new Long(sdf.format(new Date()));

        info.setCreateTime(nowLong);
        boolean save = service.updateById(info);
        if (save) {
            return json.setCode(200).setMsg("修改成功").setData(null);

        } else {
            return json.setCode(900).setMsg("修改失败").setData(null);
        }
    }


    /**
     * 根据流水号查询订单详情
     * @param param
     * @return
     */
    @PostMapping(value = "orderInfo")
    public ResultJson orderInfo(@RequestBody Map<String,String> param){
        try{
            List<Map<String,Object>> resp = invoiceService.getRelation(param.get("serialNo"), null);
            if (resp != null && resp.size() > 0){
                List<TInvoiceRelation> respList = new ArrayList<>();
                for (int i = 0; i < resp.size(); i ++){
                    TInvoiceRelation info = new TInvoiceRelation();
                    info.setId(Long.parseLong(resp.get(i).get("id").toString()));
                    info.setInvoiceApplySno(resp.get(i).get("order_no").toString());
                    info.setOrderNo(resp.get(i).get("invoice_apply_sno").toString());
                    info.setAmount(new BigDecimal(resp.get(i).get("amount").toString()));
                    info.setParkName(resp.get(i).get("park_name").toString());
                    info.setParktime(Integer.parseInt(resp.get(i).get("parktime").toString()));
                    //info.setParkCode(String.valueOf(resp.get(i).get("park_code")));
                    info.setParkCode(String.valueOf(resp.get(i).get("car_id")));
                    respList.add(info);
                }
                Page<TInvoiceRelation> list = new Page<>(1,1000);
                //分页
                List<TInvoiceRelation> invoicePageList = new ArrayList<>();
                Integer pageNumber = 1;
                Integer pageSize = 1000;
                int currIdx = (pageNumber > 1 ? (pageNumber -1) * pageSize : 0);
                for (int i = 0; i < pageSize && i < respList.size() - currIdx; i++) {
                    TInvoiceRelation invoiceDTO = respList.get(currIdx + i);
                    invoicePageList.add(invoiceDTO);
                }
                list.setTotal(respList.size());
                list.setRecords(respList);

                return ResultJson.getInstance().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
            }
        }catch (Exception e){
            logger.error("查询订单详情异常！", e);
            e.printStackTrace();
        }
        return ResultJson.getInstance().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG);
    }

    /**
     * 根据流水号查询发票详情信息
     * @param param
     * @return
     */
    @PostMapping(value = "detail")
    public ResultJson detail(@RequestBody Map<String,String> param){

        InvoiceDetailDTO result = invoiceService.selectInvoiceDetailBySerialNo(param);
        if (result != null){
            return ResultJson.getInstance().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(result);
        }
        return ResultJson.getInstance().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(result);
    }

    /**
     * 冲红（做废可以重新开发票）
     * @param req
     * @return
     */
    @PostMapping("red")
    public ResultJson red(@RequestBody InvoiceRedRequest req) {
        logger.info("v1 red:"+req.getB_trade_no());
        Map<String, Object> respMap =new HashMap<>();
        respMap.put("code", "100");
        respMap.put("msg", "冲红失败！");
        try {
            InvoiceDetailResponse resp = invoiceService.redInvoiceBW(req);
            if (resp.getCode() == 0){
                return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(true);
            }else{
                respMap.put("code", resp.getCode()+"");
                respMap.put("msg", resp.getMsg());
                return new ResultJson().setCode(ResultCode.FAIL).setMsg(resp.getMsg()).setData(false);
            }
        } catch (Exception e) {
            logger.error("冲红失败！", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(true);
        }
    }
}
